package com.zy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yomahub.liteflow.core.FlowExecutor;
import com.yomahub.liteflow.flow.LiteflowResponse;
import com.zy.bean.bo.flow.LiteFlowChainCreateBo;
import com.zy.bean.po.*;
import com.zy.bean.qo.LiteflowSearchQo;
import com.zy.bean.vo.LiteflowChainVo;
import com.zy.config.SpringContextHolder;
import com.zy.core.ElNode;
import com.zy.exception.ExpressLanguageParseException;
import com.zy.mapper.LiteflowChainMapper;
import com.zy.parser.ElParser;
import com.zy.parser.logicflow.*;
import com.zy.service.*;
import com.zy.util.PageUtil;
import com.zy.util.SnowflakeIdWorker;
import com.zy.util.UserUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.stream.Collectors;

import static org.fatewa.engine.genius.utils.GenericUtils.transaction;

/**
 * @author hanhuafeng
 * @createDate 2023-05-31 15:58:12
 * @description liteflow编排规则流程表
 */
@Service
@RequiredArgsConstructor
public class LiteflowChainServiceImpl extends ServiceImpl<LiteflowChainMapper, LiteflowChain> implements LiteflowChainService {
    private final UserUtil userUtil;
    private final EdgeService edgeService;
    private final NodeService nodeService;
    private final ChartRecordsService chartRecordsService;
    private final FlowExecutor flowExecutor;
    private final LiteflowChainMapper liteflowChainMapper;
    private final VersionListService versionListService;
    @Value("${liteflow.rule-source-ext-data-map.applicationName}")
    private String applicationName;
    private static final ObjectMapper BASE_MAPPER = new ObjectMapper();

    static {
        BASE_MAPPER.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        BASE_MAPPER.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
        BASE_MAPPER.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    }

    /**
     * 分页查询liteflow编排规则流程
     *
     * @param qo 查询入参
     * @return 分页结果
     */
    @Override
    public IPage<LiteflowChainVo> selectLiteflowChainByPage(LiteflowSearchQo qo) {
        LambdaQueryWrapper<LiteflowChain> lqw = new LambdaQueryWrapper<>();
        Page<LiteflowChain> page = this.page(qo.getPage(), lqw);
        // 将page转换为IPage<LiteflowChainVo>，主要拷贝了page的total、size、current、pages、optimizeCountSql、searchCount、records等属性
        IPage<LiteflowChainVo> result = PageUtil.copy(page, LiteflowChainVo.class);
        // 重新设置records
        List<LiteflowChain> records = page.getRecords();
        // 原有的清空
        result.getRecords().clear();
        for (LiteflowChain record : records) {
            result.getRecords().add(new LiteflowChainVo(record));
        }
        return result;
    }

    /**
     * 保存流程图
     *
     * @param chartCode        流程图编码
     * @param chartVersionCode 流程图版本编码
     * @param logicFlow        流程图
     * @return 返回编排规则的id
     * @throws JsonProcessingException json转换异常
     */
    @Override
    public String saveFlowChart(String chartCode, String chartVersionCode, LogicFlow logicFlow) throws JsonProcessingException {
        List<LfEdge> edges = logicFlow.getEdges();
        List<LfNode> nodes = logicFlow.getNodes();
        String createUserCode = userUtil.getUserCode();
        List<Edge> edgeList = getSaveEdgeList(edges, chartCode, chartVersionCode, createUserCode);
        List<Node> nodeList = getSaveNodeList(nodes, chartCode, chartVersionCode, createUserCode);
        AtomicReference<String> flowId = new AtomicReference<>("");
        transaction((manager, status) -> {
            edgeService.saveBatch(edgeList);
            nodeService.saveBatch(nodeList);
            LiteflowChain chain = getLiteflowChain(logicFlow, chartCode, chartVersionCode);
            flowId.set(chain.getChainName());
        }, SpringContextHolder.getApplicationContext());
        return flowId.get();
    }

    private LiteflowChain getLiteflowChain(LogicFlow logicFlow, String chartCode, String chartVersionCode) {
        ElParser elParser = new LogicFlowParser(logicFlow);
        ElNode elNode = elParser.extractElNode();
        LiteFlowChainCreateBo liteFlowChainCreateBo = new LiteFlowChainCreateBo();
        try {
            String sqlTemplate = elNode.generateEl();
            liteFlowChainCreateBo.setElData(sqlTemplate);
        } catch (ExpressLanguageParseException e) {
            throw new RuntimeException(e);
        }
        liteFlowChainCreateBo.setChainDesc(logicFlow.getRemark());
        liteFlowChainCreateBo.setChartCode(chartCode);
        liteFlowChainCreateBo.setChartVersionCode(chartVersionCode);
        return saveNewLiteflowChain(liteFlowChainCreateBo);
    }

    /**
     * 取保存的节点线列表
     *
     * @param edges            节点线列表
     * @param chartCode        流程图编码
     * @param chartVersionCode 流程图版本编码
     * @param createUserCode   创建人编码
     * @return 返回保存的节点线列表
     * @throws JsonProcessingException json转换异常
     */
    private List<Edge> getSaveEdgeList(List<LfEdge> edges,
                                       String chartCode,
                                       String chartVersionCode,
                                       String createUserCode) throws JsonProcessingException {
        ObjectMapper om = new ObjectMapper();
        List<Edge> edgeList = new LinkedList<>();
        for (LfEdge edge : edges) {
            Edge e = new Edge();
            e.setEdgeCode(edge.getId());
            e.setType(edge.getType());
            e.setSourceNodeCode(edge.getSourceNodeId());
            e.setTargetNodeCode(edge.getTargetNodeId());
            if (edge.getStartPoint() != null) {
                e.setStartPoint(om.writeValueAsString(edge.getStartPoint()));
            }
            if (ObjectUtils.isNotEmpty(edge.getEndPoint())) {
                e.setEndPoint(om.writeValueAsString(edge.getEndPoint()));
            }
            if (edge.getPointsList() != null) {
                e.setPointsList(om.writeValueAsString(edge.getPointsList()));
            }
            if (edge.getPointsList() != null) {
                e.setPointsList(om.writeValueAsString(edge.getPointsList()));
            }
            e.setChartCode(chartCode);
            e.setChartVersionCode(chartVersionCode);
            e.setCreateUserId(createUserCode);
            if (ObjectUtils.isNotEmpty(edge.getText())) {
                e.setLineText(om.writeValueAsString(edge.getText()));
            }
            e.setSourceAnchorId(edge.getSourceAnchorId());
            e.setTargetAnchorId(edge.getTargetAnchorId());
            if (edge.getProperties() != null) {
                e.setProperties(om.writeValueAsString(edge.getProperties()));
            }
            e.setShape(edge.getShape());
            edgeList.add(e);
        }
        return edgeList;
    }

    /**
     * 取保存的节点列表
     *
     * @param nodes            节点列表
     * @param chartCode        流程图编码
     * @param chartVersionCode 流程图版本编码
     * @param createUserCode   创建人编码
     * @return 返回保存的节点线列表
     * @throws JsonProcessingException json转换异常
     */
    private List<Node> getSaveNodeList(List<LfNode> nodes,
                                       String chartCode,
                                       String chartVersionCode,
                                       String createUserCode) throws JsonProcessingException {
        ObjectMapper om = new ObjectMapper();
        List<Node> nodeList = new LinkedList<>();
        for (LfNode node : nodes) {
            Node n = new Node();
            n.setNodeId(node.getId());
            n.setY(node.getY());
            n.setX(node.getX());
            n.setType(node.getType());
            if (node.getProperties() != null) {
                n.setProperties(om.writeValueAsString(node.getProperties()));
            }
            if (ObjectUtils.isNotEmpty(node.getText())) {
                n.setShowText(om.writeValueAsString(node.getText()));
            }
            n.setChartCode(chartCode);
            n.setChartVersionCode(chartVersionCode);
            n.setCreateUserId(createUserCode);
            if (node.getChildren() != null) {
                n.setChildren(om.writeValueAsString(node.getChildren()));
            }
            n.setShape(node.getShape());
            nodeList.add(n);
        }
        return nodeList;
    }

    /**
     * 更新流程图节点信息和规则编排信息
     *
     * @param chartCode   流程图编码
     * @param versionCode 版本编码
     * @param logicFlow   流程图
     * @return 返回编排规则的id
     * @throws JsonProcessingException json转换异常
     */
    @Override
    public String updateFlowChart(String chartCode, String versionCode, LogicFlow logicFlow) throws JsonProcessingException {
        String createUserCode = userUtil.getUserCode();
        List<LfEdge> edges = logicFlow.getEdges();
        List<LfNode> nodes = logicFlow.getNodes();
        // 转换成edgesIds
        List<String> edgesIds = edges.stream().map(LfEdge::getId).toList();
        List<String> nodesIds = nodes.stream().map(LfNode::getId).toList();
        Map<String, LfEdge> edgesMap = edges.stream().collect(Collectors.toMap(LfEdge::getId, Function.identity()));
        Map<String, LfNode> nodesMap = nodes.stream().collect(Collectors.toMap(LfNode::getId, Function.identity()));

        // 取当前流程编号、版本编号下的所有节点和边
        List<Edge> edgeList = edgeService.list(new LambdaQueryWrapper<Edge>()
                .eq(Edge::getChartCode, chartCode)
                .eq(Edge::getChartVersionCode, versionCode));
        List<String> dbEdgeList = edgeList.stream().map(Edge::getEdgeCode).toList();
        List<Node> nodeList = nodeService.list(new LambdaQueryWrapper<Node>()
                .eq(Node::getChartCode, chartCode)
                .eq(Node::getChartVersionCode, versionCode));
        List<String> dbNodeList = nodeList.stream().map(Node::getNodeId).toList();

        // edgesIds有，dbEdgeList没有的，新增
        List<String> addEdgeList = edgesIds.stream().filter(edge -> !dbEdgeList.contains(edge)).toList();
        // edgesIds没有，dbEdgeList有的，删除
        List<String> delEdgeList = dbEdgeList.stream().filter(edge -> !edgesIds.contains(edge)).toList();
        // edgesIds有，dbEdgeList有，更新
        List<String> updateEdgeList = edgesIds.stream().filter(dbEdgeList::contains).toList();


        // 根据addEdgeList，从edgesMap筛选出LfEdge，组合成List<LfEdge>
        List<LfEdge> addLfEdgeList = edgesMap.entrySet().stream()
                .filter(entry -> addEdgeList.contains(entry.getKey()))
                .map(Map.Entry::getValue)
                .toList();
        List<Edge> saveEdgeList = getSaveEdgeList(addLfEdgeList, chartCode, versionCode, createUserCode);
        // 根据updateEdgeList，从edgesMap筛选出LfEdge，组合成List<LfEdge>
        List<LfEdge> updateEdge = edgesMap.entrySet().stream()
                .filter(entry -> updateEdgeList.contains(entry.getKey()))
                .map(Map.Entry::getValue)
                .toList();

        // nodesIds有，dbNodeList没有的，新增
        List<String> addNodeList = nodesIds.stream().filter(edge -> !dbNodeList.contains(edge)).toList();
        // edgesIds没有，dbNodeList有的，删除
        List<String> delNodeList = dbNodeList.stream().filter(edge -> !nodesIds.contains(edge)).toList();
        // edgesIds有，dbNodeList有，更新
        List<String> updateNodeList = nodesIds.stream().filter(dbNodeList::contains).toList();

        // 根据addNodeList，从nodesMap筛选出LfNode，组合成List<LfNode>
        List<LfNode> addLfNodeList = nodesMap.entrySet().stream()
                .filter(entry -> addNodeList.contains(entry.getKey()))
                .map(Map.Entry::getValue)
                .toList();
        List<Node> saveNodeList = getSaveNodeList(addLfNodeList, chartCode, versionCode, createUserCode);
        // 根据updateNodeList，从edgesMap筛选出LfNode，组合成List<LfNode>
        List<LfNode> updateNode = nodesMap.entrySet().stream()
                .filter(entry -> updateNodeList.contains(entry.getKey()))
                .map(Map.Entry::getValue)
                .toList();
        AtomicReference<String> flowId = new AtomicReference<>("");
        transaction((manager, status) -> {
            // 添加Edge
            edgeService.saveBatch(saveEdgeList);
            if (ObjectUtils.isNotEmpty(delEdgeList)) {
                // 移除delEdgeList
                LambdaQueryWrapper<Edge> delEdgeWrapper = new LambdaQueryWrapper<Edge>()
                        .eq(Edge::getChartCode, chartCode)
                        .eq(Edge::getChartVersionCode, versionCode)
                        .in(Edge::getEdgeCode, delEdgeList);
                edgeService.remove(delEdgeWrapper);
            }
            // 更新Edge
            try {
                edgeService.updateEdgeByLfEdge(updateEdge, chartCode, versionCode);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            // 添加Node
            nodeService.saveBatch(saveNodeList);
            if (ObjectUtils.isNotEmpty(delNodeList)) {
                // 移除delNodeList
                LambdaQueryWrapper<Node> delNodeWrapper = new LambdaQueryWrapper<Node>()
                        .eq(Node::getChartCode, chartCode)
                        .eq(Node::getChartVersionCode, versionCode)
                        .in(Node::getNodeId, delNodeList);
                nodeService.remove(delNodeWrapper);
            }
            // 更新Node
            try {
                nodeService.updateNodeByLfNode(updateNode, chartCode, versionCode);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            // 重新生成chain
            if (ObjectUtils.isEmpty(edges) && ObjectUtils.isEmpty(nodes)) {
                // 如果给的是两个空数组，说明要清空画布
                LambdaQueryWrapper<LiteflowChain> lqw = new LambdaQueryWrapper<>();
                lqw.eq(LiteflowChain::getChartCode, chartCode);
                lqw.eq(LiteflowChain::getChartVersionCode, versionCode);
                lqw.eq(LiteflowChain::getApplicationName, applicationName);
                liteflowChainMapper.delete(lqw);
            } else {
                LiteflowChain chain = getLiteflowChain(logicFlow, chartCode, versionCode);
                flowId.set(chain.getChainName());
            }
        }, SpringContextHolder.getApplicationContext());
        // 重新加载规则
        flowExecutor.reloadRule();
        return flowId.get();
    }

    /**
     * 保存新的liteflow编排规则流程
     *
     * @param liteFlowChainCreateBo liteflow编排规则流程创建入参
     * @return 保存结果
     */
    @Override
    public LiteflowChain saveNewLiteflowChain(LiteFlowChainCreateBo liteFlowChainCreateBo) {
        // 校验chainName，用于调用，只支持英文、下划线、数字
        String chainName = SnowflakeIdWorker.getUuid();
        String chartCode = liteFlowChainCreateBo.getChartCode();
        String chartVersionCode = liteFlowChainCreateBo.getChartVersionCode();
        if (ObjectUtils.isEmpty(chartCode) || ObjectUtils.isEmpty(chartVersionCode)) {
            throw new IllegalArgumentException("流程图编号和流程图版本编号不能为空");
        }
        //// 检测ChainName是否已经存在，保证ChainName唯一
        /// synchronized (this) {
        ///    LambdaQueryWrapper<LiteflowChain> lqw = new LambdaQueryWrapper<>();
        ///    lqw.ne(LiteflowChain::getChartCode, chartCode);
        ///    lqw.ne(LiteflowChain::getChartVersionCode, chartVersionCode);
        ///    lqw.eq(LiteflowChain::getApplicationName, applicationName);
        ///    lqw.eq(LiteflowChain::getChainName, chainName);
        ///    LiteflowChain liteflowChain = this.getOne(lqw);
        ///    if (ObjectUtils.isNotEmpty(liteflowChain)) {
        ///        throw new IllegalArgumentException("chainName已经存在");
        ///    }
        ///}
        LambdaQueryWrapper<LiteflowChain> lqw = new LambdaQueryWrapper<>();
        lqw.eq(LiteflowChain::getChartCode, chartCode);
        lqw.eq(LiteflowChain::getChartVersionCode, chartVersionCode);
        lqw.eq(LiteflowChain::getApplicationName, applicationName);
        LiteflowChain liteflowChain = new LiteflowChain();
        liteflowChain.setChainDesc(liteFlowChainCreateBo.getChainDesc());
        liteflowChain.setElData(liteFlowChainCreateBo.getElData());
        boolean flag = this.update(liteflowChain, lqw);
        if (!flag) {
            liteflowChain.setChainName(chainName);
            liteflowChain.setChartCode(chartCode);
            liteflowChain.setChartVersionCode(chartVersionCode);
            liteflowChain.setApplicationName(applicationName);
            liteflowChain.setCode(SnowflakeIdWorker.getUuid());
            this.save(liteflowChain);
        } else {
            liteflowChain = this.getOne(lqw);
        }
        // 重新加载规则
        flowExecutor.reloadRule();
        return liteflowChain;
    }

    /**
     * 根据chartCode和versionCode获取流程图
     *
     * @param chartCode   流程图编码
     * @param versionCode 版本编码
     * @return 流程图
     */
    @Override
    public LogicFlow getLogicFlowLinkByCodeAndVersion(String chartCode, String versionCode) throws JsonProcessingException {
        LogicFlow result = new LogicFlow();
        // 取chart_record
        LambdaQueryWrapper<ChartRecords> chartRecordLqw = new LambdaQueryWrapper<>();
        chartRecordLqw.eq(ChartRecords::getCode, chartCode);
        ChartRecords chartRecords = chartRecordsService.getOne(chartRecordLqw);
        if (ObjectUtils.isEmpty(chartRecords)) {
            throw new IllegalArgumentException("chartCode不存在");
        }
        result.setRemark(chartRecords.getDescribe());
        // 取所有的Edge
        LambdaQueryWrapper<Edge> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Edge::getChartCode, chartCode);
        lqw.eq(Edge::getChartVersionCode, versionCode);
        List<Edge> edgeList = edgeService.list(lqw);
        List<LfEdge> lfEdgeList = new LinkedList<>();
        result.setEdges(lfEdgeList);
        // 组装
        getAllLfEdge(lfEdgeList, edgeList);
        // 取所有的node
        LambdaQueryWrapper<Node> nodeLqw = new LambdaQueryWrapper<>();
        nodeLqw.eq(Node::getChartCode, chartCode);
        nodeLqw.eq(Node::getChartVersionCode, versionCode);
        List<Node> nodeList = nodeService.list(nodeLqw);
        List<LfNode> lfNodeList = new LinkedList<>();
        result.setNodes(lfNodeList);
        // 组装
        getAllLfNodes(lfNodeList, nodeList);
        return result;
    }

    @Override
    public LiteflowResponse execute(String chainName, Object param) {
        // 检查流程是否存在
        LambdaQueryWrapper<LiteflowChain> lqw = new LambdaQueryWrapper<>();
        lqw.eq(LiteflowChain::getChainName, chainName);
        lqw.eq(LiteflowChain::getApplicationName, applicationName);
        LiteflowChain liteflowChain = this.getOne(lqw);
        if (ObjectUtils.isEmpty(liteflowChain)) {
            throw new IllegalArgumentException("当前chainName不存在");
        }
        if (ObjectUtils.isEmpty(param)) {
            return flowExecutor.execute2Resp(chainName);
        }
        return flowExecutor.execute2Resp(chainName, param);
    }

    /**
     * 复制流程图
     *
     * @param chartCode      流程图编码
     * @param oldVersionCode 旧版本编码
     * @param versionCode    新版本编码
     */
    @Override
    public void copyFlowChain(String chartCode, String oldVersionCode, String versionCode) {
        LambdaQueryWrapper<LiteflowChain> lqw = new LambdaQueryWrapper<>();
        lqw.eq(LiteflowChain::getChartCode, chartCode);
        lqw.eq(LiteflowChain::getChartVersionCode, oldVersionCode);
        List<LiteflowChain> liteflowChains = this.list(lqw);
        if (liteflowChains.isEmpty()) {
            return;
        }
        for (LiteflowChain liteflowChain : liteflowChains) {
            liteflowChain.setId(null);
            liteflowChain.setChartVersionCode(versionCode);
            liteflowChain.setCreateTime(null);
            liteflowChain.setUpdateTime(null);
            this.save(liteflowChain);
        }
    }

    /**
     * 根据规则组code执行流程
     *
     * @param chartCode 规则组code
     * @param param     入参(非必须，如果存在，则会覆盖规则组中的初始化入参)
     */
    @Override
    public LiteflowResponse executeByChartCode(String chartCode, Object param) {
        // 检查规则组是否存在
        ChartRecords chartRecords = chartRecordsService.getChartRecordsByCode(chartCode);
        if (ObjectUtils.isEmpty(chartRecords)) {
            throw new IllegalArgumentException("当前规则组不存在");
        }
        String activeVersionCode = chartRecords.getActiveVersionCode();
        if (ObjectUtils.isEmpty(activeVersionCode)) {
            throw new IllegalArgumentException("当前规则组没有激活的版本");
        }

        // 根据activeVersionCode和chartCode获取对应的liteflow规则流程
        LambdaQueryWrapper<LiteflowChain> lqw = new LambdaQueryWrapper<>();
        lqw.eq(LiteflowChain::getChartCode, chartCode);
        lqw.eq(LiteflowChain::getChartVersionCode, activeVersionCode);
        List<LiteflowChain> liteflowChains = this.list(lqw);
        if (liteflowChains.isEmpty()) {
            throw new IllegalArgumentException("当前规则组没有对应的liteflow规则流程");
        }
        for (LiteflowChain liteflowChain : liteflowChains) {
            String chainName = liteflowChain.getChainName();
            if (ObjectUtils.isNotEmpty(param)) {
                return execute(chainName, param);
            } else {
                // 根据activeVersionCode获取对应的版本配置
                VersionList versionList = versionListService.getVersionInfoByCode(activeVersionCode);
                String initParam = versionList.getInitParam();
                // 转换成map
                Map<String, Object> initParamMap = null;
                try {
                    initParamMap = BASE_MAPPER.readValue(initParam, new TypeReference<>() {
                    });
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
                return execute(chainName, initParamMap);
            }
        }
        return null;
    }

    /**
     * 取所有的lfEdge
     *
     * @param lfEdgeList 结果集
     * @param edgeList   edge集合
     * @throws JsonProcessingException json转换异常
     */
    private void getAllLfEdge(List<LfEdge> lfEdgeList, List<Edge> edgeList) throws JsonProcessingException {
        for (Edge edge : edgeList) {
            LfEdge lfEdge = new LfEdge();
            lfEdge.setCode(edge.getEdgeCode());
            lfEdge.setId(edge.getEdgeCode());
            lfEdge.setType(edge.getType());
            lfEdge.setSourceNodeId(edge.getSourceNodeCode());
            lfEdge.setTargetNodeId(edge.getTargetNodeCode());
            if (ObjectUtils.isNotEmpty(edge.getStartPoint())) {
                lfEdge.setStartPoint(BASE_MAPPER.readValue(edge.getStartPoint(), LfPoint.class));
            }
            if (ObjectUtils.isNotEmpty(edge.getEndPoint())) {
                lfEdge.setEndPoint(BASE_MAPPER.readValue(edge.getEndPoint(), LfPoint.class));
            }
            if (ObjectUtils.isNotEmpty(edge.getPointsList())) {
                lfEdge.setPointsList(BASE_MAPPER.readValue(edge.getPointsList(), new TypeReference<>() {
                }));
            }
            if (ObjectUtils.isNotEmpty(edge.getProperties())) {
                lfEdge.setProperties(BASE_MAPPER.readValue(edge.getProperties(), new TypeReference<>() {
                }));
            }
            if (ObjectUtils.isNotEmpty(edge.getLineText())) {
                lfEdge.setText(BASE_MAPPER.readValue(edge.getLineText(), LfEdge.TextEntity.class));
            }
            lfEdge.setSourceAnchorId(edge.getSourceAnchorId());
            lfEdge.setTargetAnchorId(edge.getTargetAnchorId());
            lfEdge.setShape(edge.getShape());
            lfEdgeList.add(lfEdge);
        }
    }

    /**
     * 取所有的lfNode
     *
     * @param lfNodeList 结果集
     * @param nodeList   node集合
     */
    private void getAllLfNodes(List<LfNode> lfNodeList, List<Node> nodeList) throws JsonProcessingException {
        for (Node node : nodeList) {
            LfNode lfNode = new LfNode();
            lfNode.setId(node.getNodeId());
            lfNode.setType(node.getType());
            lfNode.setX(node.getX());
            lfNode.setY(node.getY());
            if (ObjectUtils.isNotEmpty(node.getProperties())) {
                lfNode.setProperties(BASE_MAPPER.readValue(node.getProperties(), new TypeReference<>() {
                }));
            }
            if (ObjectUtils.isNotEmpty(node.getShowText())) {
                lfNode.setText(BASE_MAPPER.readValue(node.getShowText(), LfNode.TextEntity.class));
            }
            if (ObjectUtils.isNotEmpty(node.getChildren())) {
                lfNode.setChildren(BASE_MAPPER.readValue(node.getChildren(), new TypeReference<>() {
                }));
            }
            lfNode.setShape(node.getShape());
            lfNodeList.add(lfNode);
        }
    }
}




